<?php
/**
 * Created by PhpStorm.
 * User: 123
 * Date: 2020/4/21
 * Time: 10:35
 */

namespace app\common;

use app\service\DingdingServer;
use Exception;


use phpmailer\BaseException;
use think\exception\Handle;

use think\facade\Config;
use think\facade\Log;
use think\facade\Request;


class HTTP extends Handle
{
    private $code;
    private $message;
    private $errorCode;
    private $status;
    private $data;
    /**
     * 异常处理
     * @author   Devil
     * @blog    http://gong.gg/
     * @version 1.0.0
     * @date    2019-01-14
     * @desc    description
     * @param   Exception       $e [错误对象]
     */

    public function render(Exception $e)
    {



        // ($e->getLine());



        // 参数验证错误
        if($e instanceof BaseException)
        {
            $this->status = $e->status;
            $this->code = $e->code;
            $this->message = $e->message;
            $this->errorCode = $e->errorCode;
            $this->data = $e->data;
        } else {

            $this->status = false;
            $this->code = 500;
            $this->message = $e->getMessage();
            $this->errorCode = '999';
            $this->data = ['File is '=>$e->getFile(),'Line In'=>$e->getLine()];
            //  写入日志
        }
        $this->recordErrorLog($e);
        $result=[
            'msg'=>$this->message,
            'request'=>Request::url(),
            'errorCode'=>$this->errorCode,
            'status'=>$this->status,
            'code'=>$this->code,
            'data'=>$this->data,
        ];

        if(isset($e->debug)&&$e->debug)
        {
            return parent::render($e);
        }

        if(!isset($e->debug)){
            return parent::render($e);
        }

        /*
        $server = new DingdingServer();
        if(is_array($this->data))
        {
            $other=join(',',$this->data) ;
        }else{
            $other=$this->data;
        }
        $data = '[' . $this->code . ']'
            .PHP_EOL.' ErrorException in ' . Request::url()
            .PHP_EOL. ' errorCode ' . $this->errorCode
            . PHP_EOL .'message: '. $this->message
            . PHP_EOL .' Other: '.$other;
        $server->robotSend($data);
        */
        return json($result,$this->code);

    }

    protected function recordErrorLog($e){
        //  写入日志操作
        Log::init([
            'type'  =>  'File',
            'path'  =>  ROOT_PATH.'../runtime/errorlog',
            'level' => ['error']
        ]);
        $re=Log::record($e->getTraceAsString());

        Log::record($e->getMessage(),'error');

    }
}